const app = getApp();
var util = require('../../utils/util.js');
var _openid ='';
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		step: 1,
		time: '',
		openid: '',
		count: null,
		queryResult: '1',
		nickName:'',
		flag: 0,
		clockInNames: [{}],
		index:0,
		selectText:'',
		urlimage:'',
		starTime:'',
		finishTime: '',
		num: 0,
    projectId: ''
	},
	onPullDownRefresh: function () {

		wx.showNavigationBarLoading() //在标题栏中显示加载
		this.userClickInfo();
		setTimeout(function () {

			wx.hideNavigationBarLoading() //完成停止加载

			wx.stopPullDownRefresh() //停止下拉刷新

		}, 1500);
	},
	onLoad: function () {
		wx.showLoading({
			title: '加载中',
			mask: true
		})
		var that = this;
		setTimeout(
			function(){
		  _openid = app.getOpenid();
		}
			,1000)
			wx.startPullDownRefresh()
	},
	 userClickInfo: function(){
     var openid = _openid;
		 const db = wx.cloud.database();
		 var frist = 1;
		 //查询用户主页的打卡项目列表
		 db.collection('clock_project').where({
			 _openid: openid
		 }).skip(0).orderBy('main', 'desc').get({
			 success: res => {

				 if (res.data.length != 0) {
					 this.setData({
						 clockInNames: res.data
					 });
			     that.listInfo();

				 } else { frist = 0 }
				 console.log('[数据库] [查询记录] 成功 【首页打卡项目列表】: ', res.data[index]);
			 }
		 });
		 var that = this;
		 var index = this.data.index;
		 setTimeout(function () {
			 if (frist == 0) {
		 //新用户初始化
				 db.collection('clock_project').add({
					 data: {
						name: '测试计划', // 打卡名称
						signEarlyTime: '00:00', // 开始时间
						signTime: '00:00', // 截止时间
						startDay: '2021-01-00', // 开始日期
						endDay: '2025-12-00', // 截止日期
						repeat: {
							'monday': 1,
							'tuesday': 1,
							'wednesday': 1,
							'thursday': 1,
							'friday': 1,
							'saturday': 0,
							'sunday': 0
						},
						remark: '测试备注',// 备注
						imageId: '837692d3-28fc-4b8d-a4e2-2fb5ba7b0d0a' // 图片信息ID
					 },
					 success: res => {
						 that.setData({
							 clockInNames: ['测试计划']
						 })
			      that.listInfo();
					 },
					 fail: err => {
						 console.error('[数据库] [新增记录] 失败：', err)
					 }
				 })
			 }
		 }, 800)
	 },
	  listInfo(){
			const db = wx.cloud.database();
			var time = util.formatTime(new Date());
			var index = this.data.index;
			var imageId = this.data.clockInNames[index].imageId
			var name = this.data.clockInNames[index].name;
			db.collection('clock_in').where({
				_openid: this.data.openid,
				date: time.slice(0, 10),
				name: name
			}).skip(0).get({
				success: res => {
					this.setData({
						time: res.data
					});
					console.log('[数据库] [查询记录] 成功 【打卡记录】: ', res.data.length);
				},
				fail: err => {
					wx.showToast({
						icon: 'none',
						title: '查询失败！！'
					});
					console.error('[数据库] [查询记录] 失败：', err)
				}
			})
			// 查询句子和图片
			db.collection('clock_in_text').where({
				_id: imageId
			}).skip(0).get({
				success: res => {
					if (res.data.length != 0) {
						this.setData({
							selectText: res.data[0].text,
							urlimage: res.data[0].image
						});
					}
				}
			});

			this.setData({
				starTime: this.data.clockInNames[this.data.index].signEarlyTime,
				finishTime: this.data.clockInNames[this.data.index].signTime,
				num: 0,
				projectId: this.data.clockInNames[this.data.index]._id
			})
			this.onTimeInfo();
		},
		onTimeInfo: function(){
			var time = util.formatTime(new Date());
			var that = this;
			var date = that.data.time;
			var finishTime = that.data.finishTime.slice(0, 2);
			var starTime = that.data.starTime.slice(0, 2);
			if (date != '') {
				wx.showToast({
					icon: 'none',
          title: '今日该计划你已打卡！！',
          duration: 2000
				});
			} else if (time.slice(10, 13) >= finishTime){
				wx.showToast({
					icon: 'none',
          title: '今日你已错过该计划的打卡时间！！请按时打卡呦',
          duration: 2000
				});
			} else if (time.slice(10, 13) < starTime) {
				wx.showToast({
					icon: 'none',
          title: '今日还没到该计划的打卡时间！请耐心等待。。',
          duration: 2000
				});
			} else if (date==''&&time.slice(10, 13) < finishTime){
				wx.showToast({
					icon: 'none',
          title: '今日你还没打卡呦！！',
          duration: 2000
				});
			}
		},

	onAdd: function (e) {
		console.log(e)
		const db = wx.cloud.database();
		//系统时间
		var time = util.formatTime(new Date());
		//获取查询返回的时间
		var data = this.data.time;
		//打卡项目名称
		var _index = e.detail.value.clockInName;
		var name = this.data.clockInNames[_index].name
		var finishTime = this.data.finishTime.slice(0, 2);
		var starTime = this.data.starTime.slice(0, 2);

		if (data.length == 0 && time.slice(10, 13) < finishTime && time.slice(10, 13) >= starTime){
		db.collection('clock_in').add({
			data: {
				time:  new Date(time),
				nickName: this.data.nickName,
				date: time.slice(0,10),
				name: name
			},
			success: res => {
				// 在返回结果中会包含新创建的记录的 _id
				this.setData({
					time: time,
					count: 1
				})
				wx.showToast({
          title: '打卡成功',
          duration: 2000
				})
				this.clockInNum();
			},
			fail: err => {
				wx.showToast({
					icon: 'none',
          title: '打卡失败',
          duration: 2000
				})
				console.error('[数据库] [新增记录] 失败：', err)
			}
		})
		} else if (data.length != 0){
			wx.showToast({
				icon: 'none',
        title: '打卡失败，今日已打卡！！',
        duration: 2000
			});
		} else if (time.slice(10, 13) >= finishTime) {
			wx.showToast({
				icon: 'none',
        title: '打卡失败，今日你已错过该计划打卡时间！！',
        duration: 2000
			});
		} else if (time.slice(10, 13) > finishTime) {
			wx.showToast({
				icon: 'none',
        title: '打卡失败，没到打卡时间！！',
        duration: 2000
			});
		}
	},
	//统计打卡次数
	clockInNum: function(){
		var num = this.data.num + 1;
    const db = wx.cloud.database();
    db.collection('clock_project').doc(this.data.projectId).update
      ({
        data: {
          num: num
        },
        success: res => {
			  console.log("统计",num)
        },
        fail: err => {
          icon: 'none',
            console.error('[数据库] [更新记录] 失败：', err)
        }
      })
	},
	bindGetUserInfo(e) {
		this.setData({

		})
	},
	// clockProject: function(){
	// 	wx.showToast({
	// 		icon: 'none',
	// 		title: '该功能正在开发中，尽请期待！！',
	// 	})
	// },
	bindPickerChange: function(e){
		this.setData({
			index: e.detail.value
		})
		console.log("index:",e.detail.value)
		this.listInfo();
	},
	onShow: function(){

	}
})


